/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.unitn.science.matr155863_148346_145963.bccastestore.servlet;

import it.unitn.science.matr155863_148346_145963.bccastestore.DBManager;
import it.unitn.science.matr155863_148346_145963.bccastestore.items.Asta;
import it.unitn.science.matr155863_148346_145963.bccastestore.items.Offer;
import it.unitn.science.matr155863_148346_145963.bccastestore.items.User;
import it.unitn.science.matr155863_148346_145963.bccastestore.utils.AstaDetailsValidator;
import it.unitn.science.matr155863_148346_145963.bccastestore.utils.MailSender;
import it.unitn.science.matr155863_148346_145963.bccastestore.utils.OfferDetailsValidator;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.UnavailableException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;

/**
 *
 * @author Luciano
 */
public class AddOfferToDBSRV extends HttpServlet {

    private DBManager db=null;
    private static Logger log = Logger.getLogger(RegisterUserSRV.class);
    
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        try {
          db=(DBManager)super.getServletContext().getAttribute("db_manager");
        }catch(Exception e) {
            log.fatal(e);
            throw new UnavailableException(e.toString());
        }
    }
    
    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter out=response.getWriter();
        String address="/contents/public/errorPage.jsp";
        Asta asta=null;
        HttpSession session=request.getSession();
        try {
            if(request.getParameter("asta_id")==null){
                session.setAttribute("error_message", "No one asta defined");
            }else{
                Integer id=Integer.parseInt(request.getParameter("asta_id"));
                asta=db.getAsta(id);
                Offer offer = OfferDetailsValidator.createOffer(request, asta);
                offer.setAsta(asta);
                offer.setAstaId(id);
                User user=(User)request.getSession().getAttribute("user");
                offer.setBuyerId(user.getId());
                offer.setBuyer(user);
                try{
                    //Quando l asta scade se e stato aggiudicato il prodotto bisogna scalarne
                    //la quantita dal db!!!
                    String email=db.addOffer(offer);
                    /*In base al valore di id sappiamo il risultato
                      >0 offerta avvenuta con prezzo piu' alto
                      -1 offerta fatta ma ha prezzo piu' basso (L'altra aveva un 
                      *  prezzoMax piu' alto
                      -2 offerta troppo bassa
                    */
                    int status=0;//1Vittoria 0Perso
                    String mess=null;
                    if((email!=null)&&(email.equals(user.getEmail()))){
                        status=0;
                        mess="Unable to add the offer, you have to offer more money, your offer is:";
                    }else{
                        status=1;
                        mess="Offer added, your offer is:";
                    }
                    if(email!=null){
                        //Se e' la prima offerta non c'e' nessuna email da inviare
                        //DECOMMENTARE PER FAR FUNZIONARE L'INVIO DELL'EMAIL
                        sendMailToLooser(email,asta);
                    }
                    session.setAttribute("mess", mess);
                    session.setAttribute("status", status);
                    session.setAttribute("offer", offer);
                    address="/contents/user/offerDetails.jsp";
                }catch(Exception ex){
                    session.setAttribute("error_message", "You have to offer more");
                }
            }
        }catch(Exception ex){
            if(asta!=null){
                //Si e' verificato un errore durante la creazione dell'offerta
                session.setAttribute("asta",asta);
                address="/contents/user/addOffer.jsp";
                session.setAttribute("error_on", ex.getMessage());
            }else{
                //L'id inserito non e' valido
                session.setAttribute("error_message", "No valid asta defined");
            }
        } finally {    
                //RequestDispatcher dispatcher=request.getRequestDispatcher(address);
                //dispatcher.include(request, response);
            response.sendRedirect(request.getContextPath()+address);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private void sendMailToLooser(String email,Asta a) {
        String text="There is a better offer for asta:\n"
                + "Product name: "+a.getProduct().getName() 
                + "Product description: "+a.getProduct().getDescription() 
                + "Seller username: "+a.getSeller().getUsername()+"\n";
        MailSender.sendTextMailWithAutentication("daghen.de.pu@gmail.com", "daghen.de.pu", "daghendepu@gmail.com", email, "BCCAStore new offer for asta", text);
    }
}
